import {PlusOutlined,} from '@ant-design/icons';
import {Button, Drawer, FormInstance, Image, message, Popconfirm,} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import type {ActionType, ProColumns} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {ModalForm, ProFormItem, ProFormSelect, ProFormText} from '@ant-design/pro-form';
import ProDescriptions, {ProDescriptionsItemProps} from '@ant-design/pro-descriptions';
import {addData, dataList, loadData, removeData, updateData,} from './service';
import type {NoticeBody, NoticeListItem, NoticeListPagination} from './data';
import 'moment/locale/zh-cn';
import {IDomEditor, IEditorConfig, IToolbarConfig} from "@wangeditor/editor";
import {upload} from "@/services/ant-design-pro/api";
import {Editor, Toolbar} from "@wangeditor/editor-for-react";
import '@wangeditor/editor/dist/css/style.css'; // 引入 css

/**
 * 添加节点
 *
 * @param fields
 * @param mode
 */

const handleAdd = async (fields: NoticeBody, mode: boolean) => {
  const hide = message.loading(mode ? '正在保存' : '正在添加');
  try {
    mode ? await updateData({...fields}) : await addData({...fields});
    hide();
    message.success(mode ? '保存成功' : '添加成功');
    return true;
  } catch (error) {
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: NoticeListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeData(selectedRows.map((row) => row.noticeId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const submitCheckFile = (values: NoticeBody, fileName: string, dataName: string) => {
  if (values[fileName]) {
    let file = values[fileName][0];
    values[dataName] = file?.response?.data?.url || file.url;
  }
};

const NoticePage: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<NoticeListItem>();
  const columns: ProColumns<NoticeListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => {
        return [
          <a
            key="view"
            onClick={() => {
              formRef.current?.resetFields();
              setCurrentRow(record);
              setShowDetail(true);
            }}
          >
            查看
          </a>,
          <a
            key="edit"
            onClick={() => {
              formRef.current?.resetFields();
              console.log(record);
              setCurrentRow(record);
              setEditMode(true);
              handleModalVisible(true);
            }}
          >
            编辑
          </a>,
          <Popconfirm
            key="delete"
            okButtonProps={{danger: true}}
            title={`删除后无法恢复,确认删除?`}
            onConfirm={async () => {
              setCurrentRow(record);
              await handleRemove([record]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="删除"
            cancelText="取消"
          >
            <a> 删除 </a>
          </Popconfirm>,
        ];

      },
    },
    {
      title: '标题',
      dataIndex: 'noticeTitle',
    },
    {
      title: '创建时间',
      sorter: true,
      align: 'center',
      defaultSortOrder: 'descend',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '内容',
      search: false,
      dataIndex: 'noticeContent',
      ellipsis: true,
      hideInTable: true,
      // valueType: "code",
      // render: (_, record) => <span style={{whiteSpace: 'pre-wrap'}}>{record?.content}</span>,
      render: (_, record) => <div dangerouslySetInnerHTML={{__html: record?.noticeContent}}></div>,

    },
  ];

  const [editMode, setEditMode] = useState<boolean>(false);
  const [previewData, setPreviewData] = useState({
    visible: false,
    image: '',
    title: '',
  });

  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  // 编辑器内容
  const [html, setHtml] = useState("");
  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法
  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        // 自定义上传
        customUpload: async function (file: File, insertFn: any) {
          // TS 语法
          console.log(file);
          upload(file).then((value) => {
            console.log(value);
            // @ts-ignore
            insertFn(value.data.url, value.data.alt, value.data.href);
          });

          // async customUpload(file, insertFn) {                   // JS 语法
          // file 即选中的文件
          // 自己实现上传，并得到图片 url alt href
          // 最后插入图片
        },
        // withCredentials: true,
        // server: 'http://localhost:8080/enterprise/editor/upload',
        // fieldName: 'file',
        // header: {
        //   Authorization: `Bearer ${localStorage.getItem('token')}`
        // }
      },
    },
  };
  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);
  const isDev = process.env.NODE_ENV === 'development';

  return (
    <PageContainer waterMarkProps={{content: ''}}>
      <ProTable<NoticeListItem, NoticeListPagination>
        headerTitle={'通知列表'}
        actionRef={actionRef}
        rowKey="noticeId"
        search={{
          labelWidth: 120,
        }}
        options={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setEditMode(false);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={dataList}
        columns={columns}
      />
      <ModalForm<NoticeBody>
        title={currentRow?.noticeId || 0 > 0 ? '编辑通知' : '新建通知'}
        formRef={formRef}
        layout={'horizontal'}
        labelCol={{span: 4}}
        wrapperCol={{span: 18}}
        visible={createModalVisible}
        onValuesChange={(changedValues) => {
          if (changedValues && changedValues.hasOwnProperty('dateRange')) {
            formRef.current?.setFieldsValue({
              startTime: changedValues.dateRange[0] + '',
            });
            formRef.current?.setFieldsValue({endTime: changedValues.dateRange[1] + ''});
            formRef.current?.setFieldsValue({noticeTime: changedValues.dateRange[0] + "至" + changedValues.dateRange[1]});
          }
          console.log(changedValues);
        }}
        onVisibleChange={(visible) => {
          if (!visible) {
            setCurrentRow(undefined);
          }
          handleModalVisible(visible);
        }}
                  modalProps={{destroyOnClose: true, maskClosable: false}}

        onFinish={async (value) => {
          console.log(value);
          submitCheckFile(value, 'noticeFileData', 'noticeFile');
          const success = await handleAdd(value, editMode);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              // @ts-ignore
              actionRef.current?.reloadAndRest();
            }
          }
        }}
        request={async (param) => {
          console.log(param);
          if (param.noticeId > 0) {
            const {data} = await loadData(param as NoticeBody);
            setHtml(data.noticeContent)
            return data;
          } else {
            return new Promise<NoticeBody>((resolve) => {
              resolve({
                noticeId: 0,
              });
            });
          }
        }}
        params={{...currentRow}}
      >
        <ProFormText hidden name="noticeId"/>
        <ProFormText rules={[{required: true}]} label={'标题'} name="noticeTitle"/>
        {/*<ProFormTextArea rules={[{required: true}]} label={'详细内容'} name="noticeContent"/>*/}
        <ProFormItem required label={'内容'} name="noticeContent" rules={[
          {
            required: true,
            message: '内容为必填项',
          },
        ]}>
          <div style={{border: '1px solid #ccc', zIndex: 100}}>
            <Toolbar
              editor={editor}
              defaultConfig={toolbarConfig}
              mode="simple"
              style={{borderBottom: '1px solid #ccc'}}
            />
            <Editor
              defaultConfig={editorConfig}
              value={html}
              onCreated={setEditor}
              onChange={(editor) => {
                if (!editor.isEmpty()) {
                  let html1 = editor.getHtml();
                  setHtml(html1);
                  if (html1 == '') {
                  }
                  formRef.current?.setFieldsValue({noticeContent: html1});
                }

              }}
              mode="default"
              style={{height: '200px', overflowY: 'hidden'}}
            />
          </div>
          {isDev ? (<div style={{marginTop: '15px'}}>{html}</div>) : (<></>)}
        </ProFormItem>

        <ProFormSelect
          rules={[{required: true}]}
          label={'类型'}
          name="noticeType"
          initialValue={'1'}
          valueEnum={{
            '1': {
              text: '通知',
              status: 'Success',
            },
            '2': {
              text: '公告',
              status: 'Error',
            },
          }}
        />

        <ProFormText label={'文号'} name="documentNumber"/>
        <ProFormSelect
          rules={[{required: true}]}
          label={'状态'}
          name="status"
          initialValue={'0'}
          valueEnum={{
            '0': {
              text: '启用',
              status: 'Success',
            },
            '1': {
              text: '禁用',
              status: 'Error',
            },
          }}
        />
        <ProFormText hidden name="remark" initialValue={"-"}/>

      </ModalForm>

      <Image
        width={200}
        style={{display: 'none'}}
        src={previewData.image}
        preview={{
          visible: previewData.visible,
          src: previewData.image,
          onVisibleChange: (value) => {
            setPreviewData({image: previewData.image, title: '', visible: value});
          },
        }}
      />
      <Drawer
        width={800}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.noticeId && (
          <ProDescriptions<NoticeBody>
            column={1}
            bordered={true}
            title={'通知详情'}
            // @ts-ignore
            request={loadData}
            // layout={'vertical'}
            params={currentRow}
            columns={columns as ProDescriptionsItemProps<NoticeBody>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default NoticePage;
